package com.example.stujava.module.socked.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class receiver {
    public static void main(String[] args) {
        int receivePort = 10000;
        DatagramPacket packet = receiveUDP(receivePort);
        System.out.println("opposite IP:" + packet.getAddress().getHostAddress() + "opposote port:" + packet.getPort());
        String s = new String(packet.getData(), packet.getOffset(), packet.getLength());
        System.out.println("receive data is" + s);
    }

    private static DatagramPacket receiveUDP(int receivePort) {
        DatagramSocket socked = null;
        try {
            //占用端口
            socked = new DatagramSocket(receivePort);
            //等待接收数据
            byte[] bys = new byte[3 * 1024];
            DatagramPacket packet = new DatagramPacket(bys, 0, bys.length);
            socked.receive(packet); //阻塞
            System.out.println("接收完毕...");
            return packet;
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socked != null) {
                socked.close();
            }
        }
        return null;
    }
}
